//
//  MNDTabbarController.m
//  miniwangdai2
//
//  Created by 谭伟 on 2017/3/28.
//  Copyright © 2017年 谭谭伟. All rights reserved.
//

#import "MNDTabbarController.h"
#import "MNDGestureViewController.h"
#import "MNDFingerLockViewController.h"
#import "MNDMessageViewController.h"
#import "MNDAppAlertViewController.h"
#import "VTUpdateAppAlertViewController.h"

@interface MNDTabbarController ()

@end

@implementation MNDTabbarController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.hidesBottomBarWhenPushed = YES;
    //nav背景颜色
//    [[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]];
//    [self.navigationController.navigationBar setBarTintColor:[UIColor redColor]];
    [self loadCustomTabbar];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showFingerVC:) name:@"showFinger" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showGestureVC:) name:@"showGesture" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popToRootViewController:) name:@"popToRootViewControllerNotification" object:nil];
    
    //推送消息通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushMsgViewController:) name:kPushMsgIINotification object:nil];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self loadVersionInfo];
    });
    if (kDevice_iPad) {
        [[UITabBarItem appearance] setTitlePositionAdjustment:UIOffsetZero];
    }
}

- (void)loadVersionInfo {
    
    kdeclare_weakself;
    [APIManager sendRequestWithPath:API_APP_VERSION_UPDATE parameters:[MNDSign signedParamWithDict:@{@"app_type": @"ios"}] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            
            //获取当前版本号
            NSString *currentVersion = [NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
            NSString *currentVersionNum = [currentVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
            NSString *updateVersionNum = [responseModel.data[@"version_number"] stringByReplacingOccurrencesOfString:@"." withString:@""];
            NSString *forcedStr = responseModel.data[@"forced_update"];
            if ([forcedStr integerValue] == 1 && updateVersionNum.integerValue > currentVersionNum.integerValue) {
                [weakSelf showForceUpdateAlert:responseModel];
            }
            
            if([forcedStr integerValue] == -1 && updateVersionNum.integerValue > currentVersionNum.integerValue){
                [weakSelf showUpdateAlert:responseModel];
            }
        } else {
            
        }
    } onFailure:^(NSError *error) {
        
    }];
}


//版本更新弹窗
- (void)showUpdateAlert:(ResponseModel *)response{
    
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"VTUpdateAppAlertViewController" bundle:nil];
    VTUpdateAppAlertViewController *updateAlertVC = [storyBoard instantiateViewControllerWithIdentifier:@"VTUpdateAppAlertViewController"];
    updateAlertVC.contentStr = response.data[@"update_content"];
    updateAlertVC.titleStr = [NSString stringWithFormat:@"V%@版上线了",response.data[@"version_number"]];
    [self.view addSubview:updateAlertVC.view];
    [self addChildViewController:updateAlertVC];
    
    [updateAlertVC.leftButton bk_addEventHandler:^(id sender) {
    
        [updateAlertVC.view removeFromSuperview];
        [updateAlertVC removeFromParentViewController];
        
    } forControlEvents:UIControlEventTouchUpInside];
    
    [updateAlertVC.rightButton bk_addEventHandler:^(id sender) {
        [updateAlertVC.view removeFromSuperview];
        [updateAlertVC removeFromParentViewController];
        
        NSString * url = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=%@",@"1072685010"];
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:^(BOOL success) {
            
        }];
    } forControlEvents:UIControlEventTouchUpInside];
}

//强制更新版本弹窗
- (void)showForceUpdateAlert:(ResponseModel *)responseModel {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    __weak MNDAppAlertViewController *alertVC = [storyboard instantiateViewControllerWithIdentifier:[MNDAppAlertViewController description]];
    
    [self.view addSubview:alertVC.view];
    [self addChildViewController:alertVC];
    
    alertVC.versionLabel.text = [NSString stringWithFormat:@"V%@上线了", responseModel.data[@"version_number"]];
    alertVC.detailLabel.text = responseModel.data[@"update_content"];
    [alertVC.closeButton setTitle:@"立即更新" forState:UIControlStateNormal];
    
    [alertVC.closeButton bk_addEventHandler:^(id sender) {
        
        [alertVC.view removeFromSuperview];
        [alertVC removeFromParentViewController];
        NSString *urlStr =@"itms-apps://itunes.apple.com/cn/app/id1072685010?mt=8";
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
    } forControlEvents:UIControlEventTouchUpInside];
}

- (void)loadCustomTabbar {
    self.tabBar.tintColor = GlobalColor;
}

- (void)showFingerVC:(NSNotification *)notification {
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Gesture" bundle:nil];
    MNDFingerLockViewController *fingerLockVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDFingerLockViewController"];
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
    fingerLockVC.fingerTipLabel.text = [NSString stringWithFormat:@"欢迎，%@", user.user_name];
    fingerLockVC.tipLabel.text = [NSString stringWithFormat:@"欢迎，%@", user.user_name];
    [self presentViewController:fingerLockVC animated:YES completion:nil];
}

- (void)showGestureVC:(NSNotification *)notification {
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Gesture" bundle:nil];
        MNDGestureViewController *gestureViewcontroller = [storyBoard instantiateViewControllerWithIdentifier:@"MNDGestureViewController"];
        gestureViewcontroller.view.backgroundColor = [UIColor whiteColor];
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
        gestureViewcontroller.tipLabel.text = [NSString stringWithFormat:@"欢迎，%@", user.user_name];
        gestureViewcontroller.isCloseGesture = NO;
        gestureViewcontroller.topGestureView.hidden = YES;
        gestureViewcontroller.topLogImgV.hidden = NO;
//        gestureViewcontroller.isHiddenTopView = YES;
        gestureViewcontroller.navigationController.navigationBarHidden = NO;
        gestureViewcontroller.forgetGestureButton.hidden = NO;
        gestureViewcontroller.fingerBtn.hidden = NO;
        [self presentViewController:gestureViewcontroller animated:YES completion:nil];
//        [self.navigationController pushViewController:gestureViewcontroller animated:YES];
    void(^dismissVCBlock)(void) = ^(){
//        [NetworkProgressHUD showHudMsg:@"密码正确"];
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
        };
        gestureViewcontroller.dismissVCBlock = dismissVCBlock;
}

- (void)popToRootViewController:(NSNotification *)notification {
//    [self.navigationController popToRootViewControllerAnimated:YES];
//    for (UIViewController *rootViewcontroller in self.viewControllers) {
//        [rootViewcontroller.navigationController popToRootViewControllerAnimated:YES];
//    }
    [self goToLoginVC];
}

//跳转到消息控制器
- (void)pushMsgViewController:(NSNotification *)notification {
    
    NSDictionary *userInfo = notification.object;
    if ([userInfo[@"key"] isEqualToString:@"sign"]) {//签到
        self.selectedIndex = 2;
    }else if([userInfo[@"key"] isEqualToString:@"discount"]) {//加息券
        self.selectedIndex = 3;
         [[NSNotificationCenter defaultCenter] postNotificationName:kGoToDiscountVC object:userInfo];
    }else if([userInfo[@"key"] isEqualToString:@"notice"]) {
        self.selectedIndex = 0;
        [[NSNotificationCenter defaultCenter] postNotificationName:kGoToMessageVC object:userInfo];
    }else {
    
    }
    NSLog(@"打印传的参数userInfo:%@",userInfo);
}
#pragma mark 跳转到登录页面

- (void)goToLoginVC {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
    UINavigationController *naviVC = [storyboard instantiateInitialViewController];
    
    [self presentViewController:naviVC animated:YES completion:^{
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)requestSecretKey {
    
    [APIManager sendRequestWithPath:API_GET_APPKEY parameters:nil method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            [UserDefaultsTool saveObject:responseModel.data forKey:@"AppKey"];
        }
    } onFailure:^(NSError *error) {
        
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
